package com.campus.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;

import java.util.Calendar;
import java.util.Date;

/**
 * JWT工具类，方便创建、验证、获取字段值
 */
public class JWTUtil {

    // 抽离密钥
    private final static String SECRET = "ASD1123FA54F6A5S65456SD45A6";
    // 抽离过期时间的单位
    private final static int DATE_UNIT = Calendar.MINUTE;
    // 抽离过期时间的增量
    private final static int DATE_NUM = 100;
    // 抽离出用户ID字段
    private final static String ID_FIELD = "userId";

    /**
     * 创建token
     * @param userId 用户id
     * @return token
     */
    public static String createToken(Integer userId) {
        Calendar instance = Calendar.getInstance();
        instance.add(DATE_UNIT, DATE_NUM);
        Date time = instance.getTime();

        return JWT.create().withClaim(ID_FIELD, userId).withExpiresAt(time).sign(Algorithm.HMAC256(SECRET));
    }

    /**
     * 验证token有效性
     * @param token token字符串
     * @return true有效，false无效
     */
    public static boolean verifyToken(String token) {
        try {
            JWT.require(Algorithm.HMAC256(SECRET)).build().verify(token);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 通过token拿到userId
     * @param token token字符串
     * @return userId
     */
    public static Integer getUserIdByToken(String token) {
        return JWT.require(Algorithm.HMAC256(SECRET)).build().verify(token).getClaim(ID_FIELD).asInt();
    }

}
